package com.daxilong.starchen.player.adapter;

import android.content.Context;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.daxilong.starchen.player.databinding.LocalvideoListItemBinding;
import com.daxilong.starchen.player.model.MediaItem;
import com.daxilong.starchen.player.utils.Utils;

import java.util.ArrayList;
import java.util.List;

public class LocalVideoAdapter extends RecyclerView.Adapter<LocalVideoAdapter.MyHolder> {

    private List<MediaItem> dataList;
    private Context context;

    private MyListOnClickItemListener myListOnClickItemListener;

    public LocalVideoAdapter(){
        dataList = new ArrayList<>();
    }

    public void setDataList(List<MediaItem> dataList) {
        this.dataList = dataList;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        context = parent.getContext();

        LocalvideoListItemBinding binding = LocalvideoListItemBinding.inflate(LayoutInflater.from(context), parent, false);

        return new MyHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull MyHolder holder, int position) {
        MediaItem mediaItem = dataList.get(position);
        holder.bind(mediaItem);
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    class MyHolder extends RecyclerView.ViewHolder {
        private LocalvideoListItemBinding binding;
        public MyHolder(LocalvideoListItemBinding binding) {
            super(binding.getRoot());
            this.binding = binding;

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(myListOnClickItemListener !=null){
                        myListOnClickItemListener.onItemClick(getLayoutPosition());
                    }
                }
            });
        }

        public void bind(MediaItem mediaItem) {
            binding.tvName.setText(mediaItem.getName());
            binding.tvSize.setText(Formatter.formatFileSize(context,mediaItem.getSize()));
            binding.tvDuration.setText(Utils.stringForTime((int)mediaItem.getDuration()));
        }
    }

    public void setItemClientListener(MyListOnClickItemListener itemClientListener) {
        this.myListOnClickItemListener = itemClientListener;
    }

    public interface MyListOnClickItemListener{
        void onItemClick(int position);
    }

}

